package com.tg.app;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;

import com.tg.appcommon.android.TGLog;


public class SMSBroadcastReceiver extends BroadcastReceiver {

    private static final String TAG = "SMSBroadcastReceiver";
    private OnReceiveSMSListener mOnReceiveSMSListener;
    public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        TGLog.d("action=" + action);
        if (SMS_RECEIVED_ACTION.equals(action)) {
            Object[] pdus = (Object[]) intent.getExtras().get("pdus");
            if (pdus != null){
                for(Object pdu:pdus) {
                    SmsMessage smsMessage = SmsMessage.createFromPdu((byte [])pdu);
                    // 短信号码
                    String sender = smsMessage.getDisplayOriginatingAddress();

                    //短信内容
                    String content = smsMessage.getDisplayMessageBody();

                    TGLog.d(sender+"，content=" + content);
                    // 筛选
//                if ("106903561008710".equals(sender) && mOnReceiveSMSListener!= null) {
//                    Pattern pattern = Pattern.compile("\\d+");
//                    Matcher matcher = pattern.matcher(content);
//                    if(matcher.find()) {
//                        mOnReceiveSMSListener.onReceived(matcher.group());
//                    }
//                    abortBroadcast();
//                }
                }
            }

        }

    }

    /**
     * 回调接口
     */
    public interface OnReceiveSMSListener {
        void onReceived(String message);
    }


    public void setOnReceiveSMSListener(OnReceiveSMSListener onReceiveSMSListener) {
        mOnReceiveSMSListener = onReceiveSMSListener;
    }
}
